function hfile = vmr_LoadV16(hfile, v16fname)
% VMR::LoadV16  - load matching V16 file into VMRData16
%
% FORMAT:       [vmr] = vmr.LoadV16([v16fname])
%
% Input fields:
%
%       v16fname    alternative filename, otherwise use VMR's filename
%
% Output fields:
%
%       vmr         VMR object with VMRData16 field set

% Version:  v0.7b
% Build:    7090217
% Date:     Sep-02 2007, 5:31 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'vmr')
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to ''%s''.', ...
        mfilename ...
    );
end
sbc = bvqxfile_getscont(hfile.L);
bc = sbc.C;
if strcmpi(class(bc.VMRData), 'uint16')
    error( ...
        'BVQXfile:InvalidObject', ...
        'Method only defined for 8-bit VMRs.' ...
    );
end
if nargin < 2
    [vmrfname{1:3}] = fileparts(sbc.F);
    if isempty(vmrfname{2})
        error( ...
            'BVQXfile:InvalidObject', ...
            'This method only works without arguments on loaded VMRs.' ...
        );
    end
    v16fnlc = [vmrfname{1} '/' vmrfname{2} '.v16'];
    v16fulc = [vmrfname{1} '/' vmrfname{2} '.V16'];
    if exist(v16fnlc, 'file') == 2
        v16fname = v16fnlc;
    elseif exist(v16fnuc, 'file') == 2
        v16fname = v16fulc;
    else
        warning( ...
            'BVQXfile:FileNotFound', ...
            'The required, auto-linking V16 file was not found.' ...
        );
        return;
    end
elseif ~ischar(v16fname) || ...
    isempty(v16fname) || ...
    exist(v16fname(:)', 'file') ~= 2
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid V16 filename argument.' ...
    );
end
v16fname = v16fname(:)';

% try to load V16
try
    vmr16l = [];
    vmr16 = BVQXfile(v16fname);
    vmr16l = vmr16.L;
    vmr16c = bvqxfile_getcont(vmr16l);
    if ~all([bc.DimX, bc.DimX, bc.DimX] == ...
            [vmr16c.DimX, vmr16c.DimX, vmr16c.DimX])
        error('DIM_MISMATCH');
    end
catch
    bvqxfile_clear(vmr16l);
    error( ...
        'BVQXfile:BadObject', ...
        'V16 file not readable or dimension mismatch.' ...
    );
end

% copy read element
bc.VMRData16 = vmr16c.VMRData;
bvqxfile_clear(vmr16l);
bvqxfile_setcont(hfile.L, bc);
